<template>
  <view class="my-container">
    <!-- 1. 顶部用户信息区 -->
    <view class="user-info-wrap">
      <view class="avatar-wrap" @click="handleAvatarClick">
        <image :src="userAvatar" class="avatar-img" mode="aspectFill"></image>
        <view class="avatar-mask" v-if="isLogin">
          <text class="upload-text">更换头像</text>
        </view>
      </view>
      <view class="user-info">
        <text class="user-name">{{ isLogin ? userName : '未登录' }}</text>
        <text class="login-desc" v-if="!isLogin">点击登录后查看更多功能</text>
      </view>
      <view v-if="isLogin" class="sync-btn" @click="syncData">
        <text class="sync-icon">🔄</text>
        <text class="sync-text">同步数据</text>
      </view>
    </view>

    <!-- 2. 核心功能区（点赞/收藏/关注） -->
    <view class="function-grid">
      <!-- 我的点赞（合并新闻+视频） -->
      <view class="function-item" @click="openListModal('liked')">
        <text class="func-icon">❤️</text>
        <text class="item-title">我的点赞</text>
        <text class="item-count">{{ likedCount }}</text>
      </view>
      <!-- 我的收藏（仅新闻） -->
      <view class="function-item" @click="openListModal('collected')">
        <text class="func-icon">⭐</text>
        <text class="item-title">我的收藏</text>
        <text class="item-count">{{ collectedCount }}</text>
      </view>
      <!-- 我的关注（合并新闻+视频作者） -->
      <view class="function-item" @click="openListModal('followed')">
        <text class="func-icon">👥</text>
        <text class="item-title">我的关注</text>
        <text class="item-count">{{ followCount }}</text>
      </view>
    </view>

    <!-- 3. 历史浏览详情区（单独一栏） -->
    <view class="history-section" v-if="isLogin">
      <view class="section-header">
        <text class="section-title">历史浏览</text>
        <text class="clear-btn" @click="clearHistory">清空</text>
      </view>
      
      <!-- 下拉刷新 + 列表 -->
      <scroll-view 
        class="history-list" 
        scroll-y
        @refresherrefresh="onPullRefresh"
        refresher-enabled
        refresher-threshold="100"
        refresher-triggered="refreshing"
      >
        <!-- 空状态 -->
        <view class="empty-state" v-if="browseHistory.length === 0">
          <text class="empty-icon">🕒</text>
          <text class="empty-text">暂无浏览历史</text>
        </view>
        
        <!-- 浏览记录列表（兼容新闻+视频） -->
        <view 
          v-for="(item, idx) in browseHistory" 
          :key="idx"
          class="history-item"
          @click="gotoContentDetail(item)"
        >
          <!-- 封面图 -->
          <image 
            :src="item.image || '/static/tx.jpg'" 
            class="history-img"
            mode="aspectFill"
          ></image>
          <!-- 信息区 -->
          <view class="history-info">
            <text class="history-title">{{ item.title }}</text>
            <view class="history-meta">
              <text class="history-author">{{ item.author }}</text>
              <text class="history-time">{{ formatTime(item.readTime) }}</text>
              <!-- 标记类型 -->
              <text class="content-type" :class="item.type">{{ item.type === 'video' ? '视频' : '新闻' }}</text>
            </view>
          </view>
          <!-- 删除按钮 -->
          <view class="delete-btn" @click.stop="deleteHistoryItem(idx)">
            <text class="delete-icon">🗑️</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 4. 操作按钮区 -->
    <view class="btn-wrap">
      <button v-if="!isLogin" class="login-btn" type="primary" @click="gotoLoginPage">立即登录</button>
      <button v-if="isLogin" class="logout-btn" type="warn" @click="handleLogout">退出登录</button>
    </view>

    <!-- 5. 列表弹窗（点赞/收藏/关注列表） -->
    <uni-popup 
      v-model="listModalVisible" 
      type="bottom"
      :height="listModalHeight"
    >
      <view class="list-modal">
        <view class="modal-header">
          <text class="modal-title">{{ modalTitle }}</text>
          <text class="modal-close" @click="listModalVisible = false">✕</text>
        </view>
        
        <!-- 列表内容 -->
        <scroll-view class="modal-list" scroll-y>
          <view class="empty-state" v-if="currentList.length === 0">
            <text class="empty-icon">{{ getEmptyIcon() }}</text>
            <text class="empty-text">{{ getEmptyText() }}</text>
          </view>
          
          <!-- 点赞列表（合并新闻+视频） -->
          <view 
            v-if="currentListType === 'liked'"
            v-for="(item, idx) in currentList" 
            :key="idx"
            class="modal-item"
            @click="gotoContentDetail(item)"
          >
            <image 
              :src="item.image || '/static/tx.jpg'" 
              class="modal-item-img"
              mode="aspectFill"
            ></image>
            <view class="modal-item-info">
              <text class="modal-item-title">{{ item.title }}</text>
              <text class="modal-item-author">{{ item.author }} · {{ item.type === 'video' ? '视频' : '新闻' }}</text>
            </view>
          </view>
          
          <!-- 收藏列表（仅新闻） -->
          <view 
            v-if="currentListType === 'collected'"
            v-for="(item, idx) in currentList" 
            :key="idx"
            class="modal-item"
            @click="gotoContentDetail(item)"
          >
            <image 
              :src="item.image || '/static/tx.jpg'" 
              class="modal-item-img"
              mode="aspectFill"
            ></image>
            <view class="modal-item-info">
              <text class="modal-item-title">{{ item.title }}</text>
              <text class="modal-item-author">{{ item.author }} · 新闻</text>
            </view>
          </view>
          
          <!-- 关注列表（合并新闻+视频作者） -->
          <view 
            v-if="currentListType === 'followed'"
            v-for="(author, idx) in currentList" 
            :key="idx"
            class="modal-item"
            @click="gotoAuthorPage(author)"
          >
            <image 
              :src="getAuthorAvatar(author)" 
              class="modal-item-avatar"
              mode="aspectFill"
            ></image>
            <view class="modal-item-info">
              <text class="modal-item-title">{{ author }}</text>
              <text class="modal-item-desc">点击查看作者主页</text>
            </view>
            <button 
              class="unfollow-btn" 
              type="default"
              @click.stop="cancelFollowAuthor(author, idx)"
            >
              取消关注
            </button>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isLogin: false,
      userInfo: null,
      userAvatar: '/static/tx.jpg',
      userName: '',
      // 核心数据（实时同步）
      likedCount: 0,
      collectedCount: 0,
      followCount: 0,
      browseHistory: [], // 历史浏览详情列表（混合新闻+视频）
      likedContentList: [], // 点赞列表（混合新闻+视频）
      collectedNewsList: [], // 收藏新闻列表
      followedAuthorsList: [], // 关注作者列表（混合新闻+视频）
      isSyncing: false,
      refreshing: false, // 下拉刷新状态
      // 列表弹窗控制
      listModalVisible: false,
      currentListType: '', // liked/collected/followed
      currentList: [],
      modalTitle: '',
      listModalHeight: '70%', // 弹窗高度
      app: null, // 缓存App实例
      newsData: null, // 新闻基础数据
      videoData: null // 视频基础数据
    };
  },
  onShow() {
    this.app = getApp();
    this.newsData = this.app.globalData.newsData || uni.getStorageSync('newsData') || { newsDetails: {} };
    this.videoData = this.app.globalData.videoData || uni.getStorageSync('cloudVideoData') || { videoList: [] };
    this.syncGlobalData();
    // 更新 TabBar
    this.app.updateTabBarText(this.isLogin ? "我的" : "未登录");
    // 监听数据更新事件（详情页操作后同步）
    uni.$on('userDataUpdated', this.syncGlobalData);
  },
  onHide() {
    // 移除事件监听，避免内存泄漏
    uni.$off('userDataUpdated', this.syncGlobalData);
  },
  methods: {
    // 同步全局数据（核心：合并新闻+视频）
    syncGlobalData() {
      // 从App全局数据读取
      const userData = this.app.globalData.userData;
      
      // 登录状态
      this.userInfo = this.app.globalData.userInfo || uni.getStorageSync('userInfo');
      this.isLogin = !!this.userInfo;
      
      // 用户信息
      if (this.isLogin && this.userInfo) {
        this.userAvatar = this.userInfo.avatar || this.app.globalData.userSettings.avatar || '/static/pingu.jpg';
        this.userName = this.userInfo.username || '未知用户';
      } else {
        this.userAvatar = '/static/tx.jpg';
        this.userName = '';
      }
      
      // 1. 历史浏览详情（混合新闻+视频）
      this.browseHistory = Array.isArray(userData.readHistory) ? userData.readHistory : [];
      
      // 2. 点赞列表（合并新闻+视频）
      this.likedContentList = this.getLikedContentList(userData.likes);
      this.likedCount = this.likedContentList.length;
      
      // 3. 收藏新闻列表
      this.collectedNewsList = this.getNewsListByids(userData.collections, this.newsData.newsDetails);
      this.collectedCount = this.collectedNewsList.length;
      
      // 4. 关注作者列表（合并新闻+视频）
      this.followedAuthorsList = Array.isArray(userData.follows) ? userData.follows : [];
      this.followCount = this.followedAuthorsList.length;
    },

    // 获取点赞内容列表（合并新闻+视频）
    getLikedContentList(likedIds) {
      if (!Array.isArray(likedIds)) return [];
      
      const contentList = [];
      
      // 处理视频点赞
      likedIds.forEach(id => {
        if (typeof id === 'string' && id.startsWith('video_')) {
          const videoId = parseInt(id.replace('video_', ''));
          const videoItem = this.videoData.videoList.find(item => item.id === videoId);
          if (videoItem) {
            contentList.push({
              id: id,
              type: 'video',
              title: videoItem.title,
              author: videoItem.author,
              image: videoItem.cover,
              videoId: videoId
            });
          }
        } 
        // 处理新闻点赞
        else if (!isNaN(parseInt(id))) {
          const newsId = parseInt(id);
          const newsItem = this.newsData.newsDetails[newsId];
          if (newsItem) {
            contentList.push({
              id: id,
              type: 'news',
              title: newsItem.title,
              author: newsItem.author,
              image: newsItem.imageList && newsItem.imageList[0] || '',
              newsId: newsId
            });
          }
        }
      });
      
      return contentList;
    },

    // 根据 newsId 数组获取完整新闻列表
    getNewsListByids(idList, newsDetails) {
      if (!Array.isArray(idList) || !newsDetails) return [];
      return idList
        .map(id => newsDetails[id])
        .filter(news => news) // 过滤不存在的新闻
        .map(news => ({
          id: news.id,
          type: 'news',
          title: news.title,
          author: news.author,
          image: news.imageList && news.imageList[0] || '',
          publishTime: news.timedata
        }));
    },

    // 头像上传
    handleAvatarClick() {
      if (!this.isLogin) return uni.showToast({ title: '请先登录', icon: 'none' });
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.app.updateUserAvatar(res.tempFilePaths[0]);
          this.userAvatar = res.tempFilePaths[0];
          uni.showToast({ title: '头像上传成功' });
        },
        fail: () => uni.showToast({ title: '选择图片失败', icon: 'none' })
      });
    },

    // 跳登录页
    gotoLoginPage() {
      uni.navigateTo({
        url: '/pages/tabBar/tabcompage/login/login',
        fail: () => uni.redirectTo({ url: '/pages/tabBar/tabcompage/login/login' })
      });
    },

    // 退出登录
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定退出登录？',
        success: async (res) => {
          if (res.confirm) {
            await this.app.userLogout();
            this.syncGlobalData();
            this.app.updateTabBarText("未登录");
            uni.showToast({ title: '退出成功' });
          }
        }
      });
    },

    // 同步数据
    syncData() {
      if (!this.isLogin) return uni.showToast({ title: '请先登录', icon: 'none' });
      this.isSyncing = true;
      this.app.syncUserData().then(() => {
        this.isSyncing = false;
        this.syncGlobalData();
        uni.showToast({ title: '同步成功' });
      }).catch(() => {
        this.isSyncing = false;
        uni.showToast({ title: '同步失败', icon: 'none' });
      });
    },

    // 打开列表弹窗（点赞/收藏/关注）
    openListModal(type) {
      if (!this.isLogin) return uni.showToast({ title: '请先登录', icon: 'none' });
      
      switch (type) {
        case 'liked':
          this.currentListType = 'liked';
          this.currentList = this.likedContentList;
          this.modalTitle = '我的点赞';
          break;
        case 'collected':
          this.currentListType = 'collected';
          this.currentList = this.collectedNewsList;
          this.modalTitle = '我的收藏';
          break;
        case 'followed':
          this.currentListType = 'followed';
          this.currentList = this.followedAuthorsList;
          this.modalTitle = '我的关注';
          break;
      }
      this.listModalVisible = true;
    },

    // 跳转内容详情（兼容新闻+视频）
    gotoContentDetail(item) {
      if (!item) return;
      
      if (item.type === 'video') {
        // 跳转视频详情
        uni.navigateTo({
          url: `/pages/video-detail/video-detail?id=${item.videoId}`
        });
      } else {
        // 跳转新闻详情
        uni.navigateTo({
          url: `/pages/news-detail/news-detail?id=${item.newsId || item.id}`
        });
      }
    },

    // 跳转作者主页（模拟，可根据实际需求实现）
    gotoAuthorPage(authorName) {
      uni.showToast({ title: `跳转至${authorName}主页`, icon: 'none' });
      // 真实项目可跳转至作者详情页：
      // uni.navigateTo({ url: `/pages/author/author?name=${authorName}` });
    },

    // 取消关注作者（新闻+视频通用）
    cancelFollowAuthor(authorName, idx) {
      this.app.cancelFollow(authorName);
      this.followedAuthorsList.splice(idx, 1);
      this.followCount = this.followedAuthorsList.length;
      // 更新弹窗列表
      this.currentList = this.followedAuthorsList;
      uni.showToast({ title: '已取消关注', icon: 'none' });
    },

    // 清空历史浏览
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有浏览历史吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用App方法清空浏览历史
            this.app.globalData.userData.readHistory = [];
            this.app.saveUserData();
            this.browseHistory = [];
            uni.$emit('userDataUpdated');
            uni.showToast({ title: '浏览历史已清空' });
          }
        }
      });
    },

    // 删除单个浏览记录
    deleteHistoryItem(idx) {
      this.browseHistory.splice(idx, 1);
      // 同步到App的userData并保存
      this.app.globalData.userData.readHistory = this.browseHistory;
      this.app.saveUserData();
      uni.$emit('userDataUpdated');
      uni.showToast({ title: '已删除', icon: 'none' });
    },

    // 格式化时间（时间戳转本地时间）
    formatTime(timestamp) {
      if (!timestamp) return '未知时间';
      const date = new Date(timestamp);
      // 简化时间显示
      const now = Date.now();
      const diff = now - timestamp;
      if (diff < 60 * 1000) return '刚刚';
      if (diff < 60 * 60 * 1000) return `${Math.floor(diff / (60 * 1000))}分钟前`;
      if (diff < 24 * 60 * 60 * 1000) return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    // 下拉刷新
    onPullRefresh() {
      this.refreshing = true;
      setTimeout(() => {
        this.syncGlobalData();
        this.refreshing = false;
        uni.stopPullDownRefresh();
        uni.showToast({ title: '刷新成功', icon: 'none' });
      }, 800);
    },

    // 列表空状态图标
    getEmptyIcon() {
      switch (this.currentListType) {
        case 'liked': return '❤️';
        case 'collected': return '⭐';
        case 'followed': return '👥';
        default: return '🕒';
      }
    },

    // 列表空状态文本
    getEmptyText() {
      switch (this.currentListType) {
        case 'liked': return '暂无点赞内容';
        case 'collected': return '暂无收藏内容';
        case 'followed': return '暂无关注作者';
        default: return '暂无数据';
      }
    },

    // 获取作者头像
    getAuthorAvatar(authorName) {
      const avatarMap = {
        // 新闻作者
        '界面新闻': '/static/tx1.jpg',
        '常规报': '/static/tx2.jpg',
        '央视新闻': '/static/tx5.jpg',
        '人民日报': '/static/tx3.jpg',
        '新华日报': '/static/tx4.jpg',
        '桂林日报': '/static/tx6.jpg',
        // 视频作者
        '醉里挑灯看剑': '/static/avatar1.png',
        'NORA': '/static/avatar2.png',
        '动物大观察': '/static/avatar3.png'
      };
      return avatarMap[authorName] || '/static/tx.jpg';
    }
  }
};
</script>

<style scoped>
.my-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

/* 用户信息区 */
.user-info-wrap {
  background: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  position: relative;
}
.avatar-wrap {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
  position: relative;
}
.avatar-img {
  width: 100%;
  height: 100%;
}
.avatar-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,0.5);
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  padding: 10rpx 0;
}
.upload-text {
  font-size: 22rpx;
}
.user-info {
  flex: 1;
}
.user-name {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}
.login-desc {
  font-size: 24rpx;
  color: #999;
}
.sync-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: #007AFF;
  font-size: 26rpx;
  position: absolute;
  right: 30rpx;
  bottom: 30rpx;
}
.sync-icon {
  font-size: 24rpx;
  animation: spin 1s linear infinite;
  display: none;
}
.sync-btn:active .sync-icon {
  display: inline-block;
}
.sync-text {
  font-size: 24rpx;
}

/* 功能网格区 */
.function-grid {
  background: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
}
.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
  cursor: pointer;
  width: 120rpx;
}
.func-icon {
  font-size: 36rpx;
}
.item-title {
  font-size: 26rpx;
  color: #333;
  text-align: center;
}
.item-count {
  font-size: 24rpx;
  color: #999;
  background: #f5f5f5;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
}

/* 历史浏览区 */
.history-section {
  background: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}
.clear-btn {
  font-size: 24rpx;
  color: #ff4444;
  cursor: pointer;
}
.history-list {
  height: 400rpx;
}
.history-item {
  display: flex;
  align-items: center;
  gap: 15rpx;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.history-img {
  width: 100rpx;
  height: 70rpx;
  border-radius: 8rpx;
  flex-shrink: 0;
}
.history-info {
  flex: 1;
  overflow: hidden;
}
.history-title {
  font-size: 26rpx;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 5rpx;
}
.history-meta {
  display: flex;
  justify-content: space-between;
  font-size: 22rpx;
  color: #999;
  flex-wrap: wrap;
  gap: 10rpx;
}
.content-type {
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
  font-size: 20rpx;
}
.content-type.video {
  background: #e1f5fe;
  color: #0288d1;
}
.content-type.news {
  background: #f3e5f5;
  color: #7b1fa2;
}
.delete-btn {
  color: #ff4444;
  font-size: 28rpx;
  cursor: pointer;
  padding: 0 10rpx;
}
.delete-icon {
  font-size: 24rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  color: #999;
}
.empty-icon {
  font-size: 60rpx;
  margin-bottom: 20rpx;
}
.empty-text {
  font-size: 26rpx;
}

/* 按钮区 */
.btn-wrap {
  padding: 0 30rpx;
}
.login-btn, .logout-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
}

/* 列表弹窗 */
.list-modal {
  background: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 20rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.modal-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}
.modal-close {
  font-size: 32rpx;
  color: #999;
  cursor: pointer;
}
.modal-list {
  flex: 1;
  overflow-y: auto;
}
.modal-item {
  display: flex;
  align-items: center;
  gap: 15rpx;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.modal-item-img {
  width: 80rpx;
  height: 60rpx;
  border-radius: 8rpx;
  flex-shrink: 0;
}
.modal-item-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  flex-shrink: 0;
}
.modal-item-info {
  flex: 1;
  overflow: hidden;
}
.modal-item-title {
  font-size: 26rpx;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 5rpx;
}
.modal-item-author, .modal-item-desc {
  font-size: 22rpx;
  color: #999;
}
.unfollow-btn {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 22rpx;
  height: auto;
  line-height: normal;
  color: #ff4444;
  border-color: #ff4444;
}

/* 旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>